/*
 * @Author: wwssaabb
 * @Date: 2021-11-01 09:34:56
 * @LastEditTime: 2021-11-06 15:55:21
 * @FilePath: \handwritten-code\demo\发布订阅.js
 */

//发布订阅模式

class EventEmit {
  constructor() {
    this.events = {}
  }

  //订阅
  on(type, callback) {
    if (!this.events[type]) {
      this.events[type] = [callback]
    } else {
      this.events.push(callback)
    }
  }

  //取消订阅
  off(type, callback) {
    if (!this.events[type]) return
    this.events[type] = this.events[type].filter(ev => ev !== callback)
  }

  //触发事件
  emit(type) {
    this.events[type].forEach(ev => ev())
  }

  //只执行一次
  once(type, callback) {
    function fn() {
      callback()
      this.off(type, fn)
    }
    this.on(type, fn)
  }
}